package de.gwtprime.client.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;

import de.gwtprime.shared.SharedHelper;
import de.gwtprime.shared.util.Pair;


/**
 * Some app util methods
 * @author jan
 *
 */
public class AppUtils{
	
	/**
	 * Set this flag to true for client side logging
	 */
	private static boolean debug = false;

	/**
	 * Default width of all popups
	 */
	public static String popupWidth = "500px";


	/**
	 * Track an event in google analytics
	 * @param category
	 * @param action
	 * @param label
	 */
	public static native void trackEvent(String category, String action, String label) /*-{
	   $wnd.ga('send', 'event', category, action, label);
	}-*/;

	/**
	 * Track an event in google analytics
	 * @param category
	 * @param action
	 * @param label
	 * @param intArg
	 */
	public static native void trackEvent(String category, String action, String label, int intArg) /*-{
	    $wnd.ga('send', 'event', category, action, label, intArg);
	}-*/;


	/**
	 * Track a page view in google analytics
	 * @param url Visited url
	 */
	public static native void trackPageview(String url) /*-{
	    $wnd.ga('send', 'pageview', url);
	}-*/;
	
	/**
	 * Init the carousel with id '.carousel'
	 */
	public static native void initCarousel() /*-{
		$wnd.$('.carousel').carousel({hAlign:'center', vAlign:'center', hMargin:0.4, directionNav:true, buttonNav:'none', reflectionHeight:0.4,reflectionOpacity:0.4,reflection:false,shadow:false, carouselWidth:900});          
	}-*/;
	/**
	 * Validate given email with regex (on client side -> There is also a validator on server side (Helper)).
	 * @param mail
	 * @return
	 */
	public static boolean validateEmail(String mail){
		// Compile and use regular expression
		RegExp regExp = RegExp.compile(SharedHelper.emailValidationRegex);
		MatchResult matcher = regExp.exec(mail);
		return (matcher != null); // equivalent to regExp.test(inputStr); 

	}
	
	/**
	 * Convert linebreaks from a HTML text input box to HTML linebreaks
	 */
	public static String nl2br(String originalText){
		originalText = originalText.replace("\n<li>", "<li>");
		originalText = originalText.replace("</li>\n", "</li>");
		return originalText.replace("\n", "<br/>");
		
	}
	
	/**
	 * Make html save + insert <br>s
	 */
	public static String editForClient(String htmlText){
		
		htmlText = UserInputParser.escapeHTMLAndAddPrettifyTags(htmlText);
		htmlText = nl2br(htmlText);
		return htmlText;
	}
	
	/**
	 * Make html save + insert <br>s
	 */
	public static String editForClient(String htmlText, String images){
		
		htmlText = editForClient(htmlText);
		
		Map<Integer,Pair<String, String>> map = getImages(images);
		
		
		// replace e.g.: [0] with <img src="abc.png" height="300px">
		for(int key : map.keySet()){
			htmlText = htmlText.replace("["+key+"]", "<img height=\""+map.get(key).snd+"\" src=\""+map.get(key).fst+"\">");
		}
		
		return htmlText;
	}
	
	static String imageHeightDivider = "==";
	
	/**
	 * 
	 * @param images
	 * @return Map of images, first index is the index, first param of the pair, is the url, second is the height
	 */
	public static Map<Integer,Pair<String, String>> getImages(String images){
		Map<Integer,Pair<String, String>> map = new HashMap<Integer,Pair<String, String>>();
		if(images == null) return map;
		int index = 0;
		for(String s : images.split(";")){
			String[] urlAndSize = s.split(imageHeightDivider);
			
			try{
				map.put(index, new Pair<String, String>(urlAndSize[0], urlAndSize[1]));
			}catch(Exception e){
				// TODO
			}
			index++;
		}
		
		return map;
	}
	
	/**
	 * Get a list, containing only the urls of the images
	 * @param images
	 * @return
	 */
	public static List<String> getImageUrls(String images){
		
		List<String> listUrls = new ArrayList<String>();
		
		for(Pair<String, String> imgPair : getImages(images).values()){
			listUrls.add(imgPair.fst);
		}
		
		return listUrls;
	}
	
	
	/**
	 * Log on the client side to browser console. Only activated in debug mode
	 * Should not used in production! Not supported by IE!
	 * @param message
	 */
	public static void log(String message){
		if (debug) {
			consoleLog(message);
		}
	}
	
	/**
	 * 
	 * @param message
	 */
	private static native void consoleLog( String message) /*-{
	    	console.log( "me:" + message );
	}-*/;
	
	
	/**
	 * Check if the given string is null or empty
	 * @param string
	 * @return true, if given string is null or empty
	 */
	public static boolean isNullOrEmpty(String string){
		
		if(string == null || "".equals(string))
			return true;
		
		return false;
		
	}
	
	/**
	 * Used for the article section images
	 * @param images
	 * @param image
	 * @return
	 */
	public static String addImage(String images, String image){
		return AppUtils.isNullOrEmpty(images) ?  image : images + ";"+image;
	}
	
	public static String addImage(String images, String image, int height){
		
		image = image+imageHeightDivider+String.valueOf(height);
		return AppUtils.isNullOrEmpty(images) ?  image : images + ";"+image;
	}
	
	/**
	 * 
	 * @param images
	 * @return
	 */
	public static int getLastIndexOfImage(String images){
		int index = images.split(";").length-1;
		
		if(index>=0) return index;
		
		return 0;
	}
	
	/**
	 * 
	 * @param images
	 * @param index
	 * @return
	 */
	public static String getImageAtIndex(String images, int index){
		
		try{
			// entries look like https://url.de=400 -> 400 is the height in px
			return images.split(";")[index].split(imageHeightDivider)[0];
		}catch(Exception e){
			AppUtils.log("getImageAtIndex -> Out of bounds");
		}
		
		return "";
		
	}
	
	/**
	 * 
	 * @param images
	 * @param index
	 * @return
	 */
	public static String getImageHeightAtIndex(String images, int index){
		
		try{
			// entries look like https://url.de=400 -> 400 is the height in px
			return images.split(";")[index].split(imageHeightDivider)[1];
		}catch(Exception e){
			AppUtils.log("getImageAtIndex -> Out of bounds");
		}
		
		return "";
		
	}
	
	/**
	 * Manually initialize the google plus widget contained in the given container id.
	 * Also works without container id, but has to traverse complete DOM then.
	 * @param containerId
	 */
	public static native void initializeGooglePlusWidget(String containerId)/*-{
		$wnd.gapi.plusone.go(containerId);
	}-*/;
	
}
